package com.tpc.server.systeme.service;

/**
 * @version 0.0.1
 * @author frederic.fortin
 * @modified 2010-08-17
 */

import com.tpc.client.systeme.core.service.AuthentificationService;
import com.tpc.dao.extend.User;
import com.tpc.dao.extend.UserAppEngine;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tpc.server.systeme.utils.DatabaseManager;
import com.tpc.server.systeme.utils.DateManager;
import com.tpc.server.systeme.utils.SecuriteManager;
import java.io.InputStream;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class AuthentificationServiceImpl extends RemoteServiceServlet implements AuthentificationService {

    private final static Logger objLog = Logger.getLogger(AuthentificationServiceImpl.class.getName());

    public AuthentificationServiceImpl() {

    }

    private static final long serialVersionUID = 1L;

    public UserAppEngine simpleLogin(String strUsername,String strPassword,HttpServletRequest request) {
        try {
            HttpSession session = null;
            String strContextPath = request.getContextPath();
            Properties objProp = new Properties();
            Properties xtendPropeties = new Properties();
            InputStream isProperties = getClass().getClassLoader().getResourceAsStream("tpc.properties");
            objProp.load(isProperties);
            InputStream isXtendProperties = getClass().getClassLoader().getResourceAsStream("xtend_tpc.properties");
            xtendPropeties.load(isXtendProperties);
            String strResult = "denied";
            UserAppEngine user = null;
            // is user inside database and life is good ?
            DatabaseManager objBD = new DatabaseManager(objProp);           
            String sqlQuery = "SELECT user.id,firstname,lastname,groupId,organisation.id,organisation.name,organisation.OLD_ID FROM identity,user,user_has_identity,user_has_groupe,organisation_has_user,organisation "
                    + "WHERE username = ? AND password = ? AND identity.name = ? AND user.id = organisation_has_user.userId AND "
                    + "organisation_has_user.organisationId = organisation.id AND user_has_groupe.userId = user.id AND user_has_groupe.defaut = ? AND identity.life = ? "
                    + "AND identity.id = user_has_identity.identityId AND user.id = user_has_identity.userId";
            String[] arrstrParameters = {strUsername,strPassword,objProp.getProperty("IDENTITY_NAME_LOGIN"),objProp.getProperty("DEFAULT"),objProp.getProperty("ENABLE")};      
            ResultSet rs = objBD.executeQuery(sqlQuery, arrstrParameters);       
            if (rs != null) {        
                if (rs.next()) {
                    user = new UserAppEngine();
                    user.setId(rs.getInt(1));
                    user.setFirstName(rs.getString(2));
                    user.setLastName(rs.getString(3));
                    user.setUsername(strUsername);
                    user.setGroupeDefaut(rs.getInt("groupId"));
                    user.setOrganisation(rs.getInt("organisation.id"));
                    user.getOrganisation().setName(rs.getString("organisation.name"));
                    String isAdmin = "false";
                    if ((rs.getInt("groupId") == new Integer(objProp.getProperty("GROUPUSER_ADMIN")).intValue()) || (rs.getInt("groupId") == new Integer(objProp.getProperty("GROUPUSER_ADMIN")).intValue())) {
                        isAdmin = "true";
                    }
                    user.setIsAdmin(isAdmin);        
                    user.setLangue(-1,"FR");
                    strResult = strContextPath;
                    session = request.getSession(true);
                    session.setMaxInactiveInterval(7200);
                    session.setAttribute("init", "true");
                    session.setAttribute("TPC_USER_NAME",strUsername);
                    session.setAttribute("TPC_PROPERTIES", objProp);
                    session.setAttribute("TPC_XTEND_PROPERTIES",xtendPropeties);
                }
            }
            // NO MATTER WHAT INSERT INFO INTO LOGIN TABLE    
            String NOW = new DateManager().NOW(); 
            String user_id = "-1";
            String ACTION = "denied";
            if (user != null) {
                user_id = new Integer(user.getId()).toString();
                ACTION = "sucess";
            }                
            String queryLogin = "INSERT INTO user_login SET date_login = ?,username = ?,password = ?,remote_ip = ?,userId = ?,action = ?";
            String[] login_params = {NOW,strUsername,strPassword,request.getRemoteAddr(),user_id,ACTION};
            objBD.executeUpdate(queryLogin,login_params);
            
            objBD.closeConnection();
            
            strResult = strContextPath+"/ADMIN.jsp";
            
            user.setLoginPath(strResult);
            session.setAttribute("TPC_USER", user);
            return user;
        }
        catch (Exception objEX) {
            objLog.warning("Login erreur: "+objEX.getMessage());        
            return null;
        }
    }

    public User validateLogin(String strUsername,String strPassword) {
        try {
            HttpServletRequest request = this.getThreadLocalRequest();
            String strContextPath = request.getContextPath();
            Properties objProp = new Properties();
            InputStream isProperties = getClass().getClassLoader().getResourceAsStream("tpc.properties");
            objProp.load(isProperties);
            String strResult = "denied";
            User user = null;

            // is user inside database and life is good ?
            DatabaseManager objBD = new DatabaseManager(objProp);
            String sqlQuery = "SELECT user.id,firstname,lastname,groupId,organisation.id FROM identity,user,user_has_identity,user_has_groupe,organisation_has_user,organisation "
                    + "WHERE username = ? AND password = ? AND identity.name = ? AND user.id = organisation_has_user.userId AND "
                    + "organisation_has_user.organisationId = organisation.id AND user_has_groupe.userId = user.id AND user_has_groupe.defaut = ? AND identity.life = ? "
                    + "AND identity.id = user_has_identity.identityId AND user.id = user_has_identity.userId";
            String[] arrstrParameters = {strUsername,strPassword,objProp.getProperty("IDENTITY_NAME_LOGIN"),objProp.getProperty("DEFAULT"),objProp.getProperty("ENABLE")};
            ResultSet rs = objBD.executeQuery(sqlQuery, arrstrParameters);
            if (rs != null) {
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt(1));
                    user.setFirstName(rs.getString(2));
                    user.setLastName(rs.getString(3));
                    user.setUsername(strUsername);
                    user.setGroupeDefaut(rs.getInt("groupId"));
                    user.setOrganisation(rs.getInt("organisation.id"));
                    String isAdmin = "false";
                    if (rs.getInt("groupId") == new Integer(objProp.getProperty("GROUP_ADMINISTRATEUR")).intValue()) {
                        isAdmin = "true";
                    }
                    user.setIsAdmin(isAdmin);
                    user.setLangue(-1,"EN");
                    strResult = strContextPath;
                    HttpSession session = request.getSession(true);
                    session.setMaxInactiveInterval(7200);
                    session.setAttribute("init", "true");
                    session.setAttribute("TPC_USER", user);
                    session.setAttribute("TPC_PROPERTIES", objProp);
                }
            }
            objBD.closeConnection();

            if (user.getGroupeDefaut() == new Integer(objProp.getProperty("GROUP_ADMINISTRATEUR")).intValue()) {
                strResult = strContextPath+"/ADMIN.jsp";
            }
            else if (user.getGroupeDefaut() == new Integer(objProp.getProperty("GROUP_DIRECTEUR")).intValue()) {
                strResult = strContextPath+"/ADMIN.jsp";
            }
            else {
                strResult = strContextPath+"/AFFICHAGE.jsp";
            }
            user.setLoginPath(strResult);
            return user;
        }
        catch (Exception objEX) {
            objLog.info(objEX.getMessage());
            return null;
        }
    }

    public String logout() {
        try {
            HttpServletRequest request = this.getThreadLocalRequest();
            HttpSession session = request.getSession(false);
            session.invalidate();
        }
        catch (Exception e) {
            
        }
        return null;
    }

    public Boolean validateAdmin(String id) {
        try {
            Boolean blnAccess = false;
            SecuriteManager objSecurite = new SecuriteManager(this.getThreadLocalRequest());
            DatabaseManager objBD = objSecurite.getDataBaseManager();
            String sqlQuery = "SELECT userId FROM user_has_group WHERE groupId = ? AND userId = ?";
            String[] param = {objSecurite.getProperties().getProperty("GROUP_DIRECTOR"),new Integer(objSecurite.getUser().getId()).toString()};
            ResultSet objRS = objBD.executeQuery(sqlQuery,param);
                if (objRS != null) {
                    if (objRS.next()) {
                        blnAccess = true;
                    }
                }
            objBD.closeConnection();
            return blnAccess;
        }
        catch (Exception e) {
            objLog.info("message : "+e.getMessage());
            return null;
        }
    }

}